﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Jint.Native;
using jsweb.ContentTypes;

namespace jsweb
{
   class Program
   {
      static HttpProvider httpProvider = new HttpProvider();
      static MVC mvc = new MVC();
      static BinaryContent _binaryContentTypeProvider = new BinaryContent();
      static HtmlContent _htmlContentTypeProvider = new HtmlContent(mvc);
      
      static void Main(string[] args)
      {
         httpProvider.IncomingRequest += new HttpProvider.DelHttpContext(httpProvider_IncomingRequest);
         httpProvider.Listen("http://*:12345/");

         while(true)
         {
            Console.ReadLine();
         }
      }

      static void HandleContent(HttpListenerContext context)
      {
         string errorMessage = string.Empty;

         try
         {
            // TODO: Implement content routing
            // Check for match with actions
            if(!_htmlContentTypeProvider.HandleContent(context))
            {
               // Try binary
               _binaryContentTypeProvider.HandleContent(context);
            }
         }
         catch (Exception ex)
         {
            errorMessage =
               "<h2>Please see below for details</h2>" + ex.ToString();
            context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
         }

         // Check for error
         if(context.Response.StatusCode != (int)HttpStatusCode.OK)
         {
            // Return error-page
            StreamWriter streamWriter = new StreamWriter(context.Response.OutputStream);
            var errorCode = context.Response.StatusCode + " - " +
                               Enum.GetName(typeof (HttpStatusCode), context.Response.StatusCode);
            streamWriter.Write("<html><head><title>" + errorCode + "</title>" +
                              "</head><body><h1>" + errorCode + "</h1>" + 
                              errorMessage +
                              "</body></html>");
            streamWriter.Flush();
            streamWriter.Close();
         }
         context.Response.Close();
      }

      /// <summary>
      /// Occurs when a user agent requests a resource
      /// </summary>
      /// <param name="context"></param>
      static void httpProvider_IncomingRequest(HttpListenerContext context)
      {
         Console.WriteLine("Agent requests " + context.Request.Url);
         HandleContent(context);
      }
   }
}
